package org.xjtu.weteam.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.common.utils.imageUtil;
import org.xjtu.weteam.mapper.UserMapper;
import org.xjtu.weteam.model.domain.User;
import org.xjtu.weteam.model.dto.UserDTO;
import org.xjtu.weteam.service.UserService;

import java.io.IOException;

/**
 * UserServiceImpl 将自动获得 IService 中定义的所有通用服务方法，比如保存、删除、更新和查询等
 * @author Kevin
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User authenticate(Integer id, String password) {
        User user = userMapper.selectById(id);
        if (user != null) {
            return user;
        }
        return null;
    }

    public User findByOpenid(String openid){
        return userMapper.findByOpenid(openid);
    }

    public void insertByOpenId(User user){
        userMapper.insertByOpenId(user);
    }

    public UserDTO getUserInfoByToken(String token) {
        Integer userId = TokenUtils.getIdFromToken(token);
        if (userId == null) {
            return null;
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }
        UserDTO userDTO = new UserDTO()
                .setUserId(user.getUserId())
                .setNickname(user.getNickname());
        try {
            userDTO.setImage(imageUtil.getAvatar(user.getImagePath()));
        } catch (IOException e) {
            e.printStackTrace();
            userDTO.setImage(null);
        }
        return userDTO;
    }

    @Override
    public boolean getUserId(String name) {
        return userMapper.getUserId(name);
    }


    public void setUserInfoByToken(String token, String userName, String imagePath) {
        Integer userId = TokenUtils.getIdFromToken(token);
        if (imagePath == null || imagePath.isEmpty()) {
            userMapper.updateNameById(userId, userName);
        } else {
            userMapper.updateUserById(userId, imagePath, userName);
        }
    }

    @Override
    public String getUserName(Integer id) {
        return "";
    }


}
